<template>
	<view class="user-chat">
		<scroll-view id="scrollview" scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true"
		:style="{height:style.contentH + 'px'}">
			<block v-for="(item, index) in list" :key="index">
				<!-- 聊天列表 -->
				<user-chat-list :item="item" :index="index"></user-chat-list>
			</block>
		</scroll-view>
		<!-- 输入框 -->
		<user-chat-bottom @submit="submit"></user-chat-bottom>
	</view>
</template>

<script>
import userChatBottom from '../../components/user-chat/user-chat-bottom.vue';
import userChatList from '../../components/user-chat/user-chat-list.vue';
import settime from '../../common/time.js'
export default {
	data() {
		return {
			list: [],
			scrollTop: 0,
			style: {
				contentH: 0,
				itemH: 0
			}
		};
	},
	methods: {
		initdata() {
			try{
				const res = uni.getSystemInfoSync()
				this.style.contentH = res.windowHeight - uni.upx2px(123)
			}catch(e){
				//TODO handle the exception
			}
		},
		pageToBottom() {
			let q = uni.createSelectorQuery();
			q.select('#scrollview').boundingClientRect();
			q.selectAll('.user-chat-list-content').boundingClientRect();
			q.exec((res) => {
				res[1].forEach((ret) => {
					this.style.itemH += ret.height
					console.log(ret.height)
				});
				if(this.style.itemH > this.style.contentH){
					this.scrollTop = this.style.itemH
				}
			})
			 
		},
		submit(data) {
			if(data !== ""){
				// 构建数据
				let now = new Date().getTime();
				let obj = {
					isme: true,
					userpic: '../../static/demo/userpic/10.jpg',
					type: 'text',
					data: data,
					time: now,
					gstime: settime.gettime.getChatTime(now, this.list[this.list.length-1].time)
				}
				this.list.push(obj)
				this.pageToBottom()
			}
		},
		// 获取聊天数据
		getdata() {
			// 从服务器获取到的数据
			let arr = [
				{
					isme: false,
					userpic: '../../static/demo/userpic/12.jpg',
					type: 'text',
					data: '哈哈',
					time: '1589905609'
				},
				{
					isme: true,
					userpic: '../../static/demo/userpic/11.jpg',
					type: 'img',
					data: '../../static/demo/3.jpg',
					time: '1589906609'
				}
			];
			for(let i = 0; i < arr.length; i++){
				arr[i].gstime = settime.gettime.getChatTime(arr[i].time, i > 0? arr[i-1].time:0)
			}
			this.list = arr
		}
	},
	onLoad() {
		this.getdata()
		this.initdata()
	},
	onReady() {
		this.pageToBottom()
	},
	components: {
		userChatBottom,
		userChatList
	}
};
</script>

<style scoped lang="scss">
.user-chat {
	width: 100%;
}
</style>
